package org.bot.http.client;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.Consts;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.config.AuthSchemes;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Author 沧月
 * @CreateTime 2023/4/18 20:08
 * @Version v1.0.0
 * @Description
 */

public class HttpTool {

    private static JSONObject httpClient(HttpUriRequest request, CookieStore cookieStore) {
        String body = "";
        CloseableHttpClient client = sslClient(cookieStore);
        try {
            // 执行请求操作，并拿到结果（同步阻塞）
            CloseableHttpResponse response = client.execute(request);
            // 获取结果实体
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                // 按指定编码转换结果实体为String类型
                body = EntityUtils.toString(entity, "UTF-8");
            }
            EntityUtils.consume(entity);
            response.close();
            return JSONObject.parseObject(body);
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        } finally {
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
                return new JSONObject().fluentPut("code", -1).fluentPut("msg", "系统错误!");
            }
        }
    }

    public static String downloadFile(String url) {
        return downloadFile(url, null);
    }

    public static String downloadFile(String url, CookieStore cookieStore) {
        HttpGet request = new HttpGet(url);
        CloseableHttpClient client = sslClient(cookieStore);
        // 执行请求操作，并拿到结果（同步阻塞）
        CloseableHttpResponse response = null;
        try {
            response = client.execute(request);
            // 检查响应状态码
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                // 获取 Content-Disposition 头部
                Header contentDispositionHeader = response.getFirstHeader("Content-Disposition");
                // 从 Content-Disposition 头部中提取文件名
                String fileName = extractFileName(contentDispositionHeader.getValue());
                // 获取文件内容
                byte[] fileContents = EntityUtils.toByteArray(response.getEntity());

                // 保存文件到本地
                String fileSavePath = System.getProperty("user.dir") + "/download";
                File folder = new File(fileSavePath);
                if (!folder.exists()) {
                    folder.mkdirs();
                }

                String localFilePath = fileSavePath + "/" + fileName;
                try (FileOutputStream fos = new FileOutputStream(localFilePath)) {
                    fos.write(fileContents);
                }
                return localFilePath;
            } else {
                throw new RuntimeException("下载文件失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            try {
                response.close();
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    private static String extractFileName(String contentDisposition) {
        String fileName = null;
        Pattern pattern = Pattern.compile("filename=\"(.*?)\"");
        Matcher matcher = pattern.matcher(contentDisposition);

        if (matcher.find()) {
            fileName = matcher.group(1);
        }
        return fileName;
    }


    public static JSONObject doGet(String url) {
        return doGet(url, null);
    }

    public static JSONObject doGet(String url, CookieStore cookieStore) {
        HttpGet httpGet = new HttpGet(url);
        return httpClient(httpGet, cookieStore);
    }

    public static JSONObject doPost(String url, JSONObject body, CookieStore cookieStore) {
        // 创建post方式请求对象
        HttpPost httpPost = new HttpPost(url);
        List<NameValuePair> form = new ArrayList<>();
        body.forEach((k, v) -> {
            form.add(new BasicNameValuePair(k, body.getString(k)));
        });
        httpPost.setEntity(new UrlEncodedFormEntity(form, Consts.UTF_8));
        return httpClient(httpPost, cookieStore);
    }


    /**
     *  提交JSON 方式
     * @param url
     * @param body
     * @param cookieStore
     * @return
     */
    public static JSONObject doJsonPost(String url, JSONObject body, CookieStore cookieStore) {
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Content-Type", "application/json");
        httpPost.setEntity(new StringEntity(body.toString(), Consts.UTF_8));
        return httpClient(httpPost, cookieStore);
    }

    public static JSONObject doPost(String url, JSONObject body) {
        return doPost(url, body, null);
    }

    private static CloseableHttpClient sslClient(CookieStore cookieStore) {
        try {
            // 在调用SSL之前需要重写验证方法，取消检测SSL
            X509TrustManager trustManager = new X509TrustManager() {
                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                @Override
                public void checkClientTrusted(X509Certificate[] xcs, String str) {
                }

                @Override
                public void checkServerTrusted(X509Certificate[] xcs, String str) {
                }
            };
            SSLContext ctx = SSLContext.getInstance(SSLConnectionSocketFactory.TLS);
            ctx.init(null, new TrustManager[]{trustManager}, null);
            SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(ctx, NoopHostnameVerifier.INSTANCE);
            // 创建Registry
            RequestConfig requestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD_STRICT)
                    .setExpectContinueEnabled(Boolean.TRUE).setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST))
                    .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)).build();
            Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("http", PlainConnectionSocketFactory.INSTANCE)
                    .register("https", socketFactory).build();
            // 创建ConnectionManager，添加Connection配置信息
            PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
            HttpClientBuilder httpClientBuilder = HttpClients.custom().setConnectionManager(connectionManager);
            httpClientBuilder.setDefaultRequestConfig(requestConfig);
            if (cookieStore != null) {
                httpClientBuilder.setDefaultCookieStore(cookieStore);
            }
            return httpClientBuilder.build();
        } catch (KeyManagementException ex) {
            throw new RuntimeException(ex);
        } catch (NoSuchAlgorithmException ex) {
            throw new RuntimeException(ex);
        }
    }

}

